<template>
  <div>
    <a-modal
      ok-text="确认"
      cancel-text="取消"
      :maskClosable="false"
      :title="title + '销售订单'"
      :width="modalWidth"
      @cancel="handleClose"
      :destroyOnClose="true"
      :visible="visible"
      :confirmLoading="confirmLoading"
      @ok="onSubmit"
      footer=""
    >
      <template>
        <div class="modalBut">
          <a-button @click="handleClose">
            取消
          </a-button>
          <a-button @click="onSubmit" type="primary">确认</a-button>
        </div>
      </template>
      <div
        :style="{
          width: '100%',
          border: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
        }"
      >
        <a-spin :spinning="confirmLoading">
          <a-form-model ref="ruleForm" :model="model" :rules="rules">
            <a-row>
              <a-row :gutter="24">
                <a-col :span="6">
                  <a-form-model-item
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    label="订单号"
                    hasFeedback
                    prop="orderNumber"
                  >
                    <a-input
                      placeholder="请输入订单号"
                      v-model.trim="model.orderNumber"
                    />
                  </a-form-model-item>
                </a-col>

                <a-col :span="6">
                  <a-form-model-item
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    label="客户"
                    hasFeedback
                    prop="customer"
                  >
                    <a-select
                      :open="false"
                      :defaultOpen="false"
                      mode="multiple"
                      :allowClear="true"
                      placeholder="客户"
                      v-model="model.customer"
                      @dropdownVisibleChange="handleDepar"
                      @change="handleDeparChange"
                    >
                      <a-select-option
                        v-for="item in tableOption"
                        :key="item.id"
                        :value="item.id"
                      >
                        {{ item.customerName }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col :span="6">
                  <a-form-model-item
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    label="客户单号"
                    hasFeedback
                    prop="customerOrderCode"
                  >
                    <a-input
                      placeholder="请输入客户单号"
                      v-model="model.customerOrderCode"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="6">
                  <a-form-model-item
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    label="销售员"
                    hasFeedback
                    prop="salesPerson"
                  >
                    <a-select
                      :open="false"
                      :defaultOpen="false"
                      mode="multiple"
                      :allowClear="true"
                      placeholder="销售员"
                      v-model="model.salesPerson"
                      @dropdownVisibleChange="handlePerson"
                      @change="handlePersonChange"
                      @search="handleSearch"
                    >
                      <a-select-option
                        v-for="item in tableUserOption"
                        :key="item.id"
                        :value="item.id"
                      >
                        {{ item.name }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24">
                <a-col :span="6">
                  <a-form-model-item
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    label="备注"
                    hasFeedback
                    prop="remarks"
                  >
                    <a-input placeholder="请输入备注" v-model="model.remarks" />
                  </a-form-model-item>
                </a-col>

                <a-col :span="6">
                  <a-form-model-item
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    label="送货地址"
                    hasFeedback
                    prop="address"
                  >
                    <a-input
                      placeholder="请输入送货地址"
                      v-model="model.address"
                    />
                  </a-form-model-item>
                </a-col>

                <a-col :span="6">
                  <a-form-model-item
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    label="发票号"
                    hasFeedback
                    prop="invoiceNo"
                  >
                    <a-input
                      placeholder="请输入发票号"
                      v-model="model.invoiceNo"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="6">
                  <a-form-model-item
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    label="收款账号"
                    hasFeedback
                    prop="collectionAccount"
                  >
                    <a-input
                      placeholder="请输入收款账号"
                      v-model="model.collectionAccount"
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24">
                <a-col :span="6">
                  <a-form-model-item
                    label="送货日期"
                    prop="plannedDeliveryDate"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    placeholder="请选择计划送货日期"
                  >
                    <a-date-picker
                      :showToday="false"
                      style="width:100%"
                      placeholder="请选择计划送货日期"
                      v-model="model.plannedDeliveryDate"
                      @change="changepPannedDeliveryDate"
                      :format="dateFormat"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="6">
                  <a-form-model-item
                    label="订单日期"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    placeholder="请选择订单日期"
                    prop="orderDate"
                  >
                    <a-date-picker
                      :showToday="false"
                      placeholder="请选择订单日期"
                      style="width:100%"
                      v-model="model.orderDate"
                      @change="changeOrderDate"
                      :format="dateFormat"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="6">
                  <a-form-model-item
                    label="收款日期"
                    prop="plannedCollectionDate"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    placeholder="请选择计划收款日期"
                  >
                    <a-date-picker
                      :showToday="false"
                      placeholder="请选择计划收款日期"
                      style="width:100%"
                      v-model="model.plannedCollectionDate"
                      @change="changePlannedCollectionDate"
                      :format="dateFormat"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="6">
                  <a-form-model-item
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    label="结算币种"
                    hasFeedback
                    prop="settlementCurrency"
                  >
                    <a-input
                      placeholder="请输入结算币种"
                      v-model="model.settlementCurrency"
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24">
                <a-col :span="6">
                  <a-form-model-item
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    label="总金额"
                    prop="totalAmount"
                  >
                    <a-input
                      placeholder="请输入总金额"
                      v-model="model.totalAmount"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="6">
                  <a-form-model-item
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    label="收款金额"
                    prop="amountCollected"
                  >
                    <a-input
                      placeholder="请输入收款金额"
                      v-model="model.amountCollected"
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-row>

            <!-- 商品表格 -->
            <a-row>
              <GoodTable ref="goodTable" @ok="modalTbale"></GoodTable>
            </a-row>
          </a-form-model>
        </a-spin>
      </div>
      <table-select-modal
        ref="selectForm"
        :columns="customerModel.columns"
        :tableKey="customerModel.tableKey"
        :treeKey="customerModel.treeKey"
        @tableSelect="tableSelect"
        :replaceFields="customerModel.replaceFields"
        :searchKey="customerModel.searchKey"
        :name="customerModel.name"
        :code="customerModel.code"
        :filename="customerModel.filename"
      ></table-select-modal>
      <table-Modal
        ref="tableForm"
        :columns="userModel.columns"
        :tableKey="userModel.userTableKey"
        :treeKey="userModel.userTreeKey"
        @tableSelect="tableSelectUser"
        :replaceFields="userModel.userReplaceFields"
        :searchKey="userModel.userSearchKey"
        :name="userModel.userName"
        :filename="userModel.userfilename"
      ></table-Modal>
    </a-modal>
  </div>
</template>

<script>
import api from "@/api/apiServer";
import { isNum } from "@/unit/rule.js";
import TableSelectModal from "@/components/TableSelectModal";
import TableModal from "@/components/TableSelectModal";
import {
  customerModel,
  userModel,
} from "@/pages/OrderMent/components/tableConfig";

import GoodTable from "@/pages/OrderMent/components/GoodTable.vue";

export default {
  components: { TableSelectModal, TableModal, GoodTable },
  data() {
    return {
      title: "", // 标题
      visible: false, // 状态、
      modalWidth: 1677, // 抽屉宽度
      model: {},
      show: true, //根据菜单类型，动态显示隐藏表单元素
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      dateFormat: "YYYY-MM-DD",
      wareHouseList: [],
      tableOption: [],
      tableUserOption: [],
      customerModel,
      userModel,
    };
  },
  computed: {
    rules() {
      return {
        orderNumber: [{ required: true, message: "请输入订单号!" }],
        customer: [{ required: true, message: "请输入客户!", trigger: "blur" }],
        wareHouse: [{ required: true, message: "请输入销售仓库!" }],
        amountCollected: [{ validator: isNum, trigger: "change" }],
        totalAmount: [{ validator: isNum, trigger: "change" }],
        homeCurrency: [{ validator: isNum, trigger: "change" }],
        exchangeRate: [{ validator: isNum, trigger: "change" }],
      };
    },
  },
  watch: {
    checkedKeys(val) {
      console.log("onCheck", val);
    },
  },
  mounted() {
    this.getWareHouseList();
  },
  methods: {
    // 新增
    modalAdd() {
      this.modalEdit(this.model);
    },
    // 编辑
    modalEdit(record) {
      this.resetScreenSize();
      this.visible = true;
      console.log(record, "oo");
      if (record.id) {
        if (record.salesPerson == null) {
          delete record.salesPerson;
        }
        this.getCustomerAllList();
        this.getUserAllList();
      }
      this.model = Object.assign({}, record);
      if (this.model.goodsIds !== null && this.model.goodsIds !== "") {
        this.getCommodityList();
      }
    },
    // 商品选择回调
    modalTbale(goodsIds) {
      this.$set(this.model, "goodsIds", goodsIds);
    },
    // 商品查询
    async getCommodityList() {
      let params = {
        pageNumber: 1,
        pageSize: 99,
        deleteFlag: "N",
        goodsIds: this.model.goodsIds,
      };
      const res = await api.CommodityList(params);
      let newArr = this.model.goodsIds.split(",");
      this.$refs.goodTable.selectedRowKeys = newArr.map((item) => {
        return Number(item);
      });
      this.$refs.goodTable.tableData = res.data.data;
    },
    onChangeMenuType() {},
    // 关闭
    handleClose() {
      this.visible = false;
      this.$refs.ruleForm.resetFields();
      this.model = Object.assign({});
    },
    // 获取销售员数据
    async getUserAllList() {
      let params = { pageNumber: 1, pageSize: 99999, deleteFlag: "N" };
      const res = await api.UserList(params);
      this.tableUserOption = res.data.data;
    },
    // 获取客户数据
    async getCustomerAllList() {
      let params = { pageNumber: 1, pageSize: 99999, deleteFlag: "N" };
      const res = await api.customerPageList(params);
      this.tableOption = res.data.data;
    },
    onSubmit() {
      const that = this;
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          that.handleSubmit();
        } else {
          return false;
        }
      });
    },

    // 时间格式化
    changeOrderDate(date, dateString) {
      this.model.orderDate = dateString;
    },
    changepPannedDeliveryDate(date, dateString) {
      this.model.plannedDeliveryDate = dateString;
    },
    changePlannedCollectionDate(date, dateString) {
      this.model.plannedCollectionDate = dateString;
    },

    async handleSubmit() {
      let res;
      if (Array.prototype.isPrototypeOf(this.model.salesPerson)) {
        this.model.salesPerson = null;
      }
      this.confirmLoading = true;
      this.model.directCollection = true;
      this.model.directDelivery = true;
      if (this.model.id) {
        res = await api.orderEdit(this.model); //修改
      } else {
        res = await api.orderAdd(this.model); //新增
      }
      if (res.code && res.code !== 200) {
        this.$message.error(res.message);
        this.confirmLoading = false;
        return;
      }
      this.$message.success(res.message);
      this.confirmLoading = false;
      this.$emit("ok");
      this.visible = false;
    },
    // 根据屏幕变化,设置抽屉尺寸
    resetScreenSize() {
      let screenWidth = document.body.clientWidth;
      if (screenWidth < 500) {
        this.modalWidth = screenWidth;
      } else {
        this.modalWidth = 1677;
      }
    },
    handleDepar() {
      this.$refs.selectForm.title = "客户";
      this.$refs.selectForm.modalAdd();
      if (this.model.customer) {
        let arr = this.model.customer.toString().split(",");
        if (arr.length > 0) {
          let newArr = arr.map((item) => {
            return Number(item);
          });
          this.$refs.selectForm.selectedRowKeys = newArr;
        } else {
          this.$refs.selectForm.selectedRowKeys = [];
        }
      }
    },
    handlePerson() {
      this.$refs.tableForm.title = "人员";
      this.$refs.tableForm.modalAdd();
      if (this.model.salesPerson) {
        let arr = this.model.salesPerson.toString().split(",");
        if (arr.length > 0) {
          let newArr = arr.map((item) => {
            return Number(item);
          });
          this.$refs.tableForm.selectedRowKeys = newArr;
        } else {
          this.$refs.tableForm.selectedRowKeys = [];
        }
      }
    },
    handlePersonChange(value) {
      console.log(value, "变化");
      if (value.length > 0) {
        this.model.salesPerson = value.toString();
      } else {
        this.model.salesPerson = value;
      }
    },
    tableSelect(result, tableOption) {
      console.log(result);
      this.tableOption = tableOption;
      this.$set(this.model, "customer", result[0].id);
      this.$refs.ruleForm.clearValidate(["customer"]);
    },
    tableSelectUser(result, tableUserOption) {
      this.tableUserOption = tableUserOption;
      console.log(result);
      this.$set(this.model, "salesPerson", result[0].id);
    },
    handleDeparChange(value) {
      if (value.length > 0) {
        this.model.customer = value.toString();
      } else {
        delete this.model.customer;
      }
    },
    //获取仓库
    async getWareHouseList() {
      var params = {};
      const res = await api.wareHouseList(params);
      this.wareHouseList = res.data;
    },
    handleSearch() {
      console.log(1);
    },
  },
};
</script>

<style lang="less" scoped></style>
